package com.auerdi.ui.detail;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.auerdi.R;
import com.auerdi.ui.detail.repo.Repo;
import com.auerdi.ui.detail.ui.ExpandableHeader;
import com.auerdi.ui.detail.ui.ExpandableLayout;
import com.auerdi.ui.detail.utils.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.Actis;
import com.example.egghttp.retrofit.beans.banner.OffcerDetail;
import com.example.egghttp.retrofit.beans.banner.OffcerDetailRe;
import com.example.egghttp.retrofit.beans.banner.ProinfosCon;
import com.example.egghttp.retrofit.beans.goods.Product;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;

/**
 * Created by YoKeyword on 16/2/14.
 */
public class ADProductDetailRedFragment extends SwipeBackFragment {


    private static Product mProduct;
    @BindView(R.id.viewPager)
    ViewPager mHeaderPager;
    @BindView(R.id.exp_header)
    ExpandableHeader mExpHeader;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerview;
    @BindView(R.id.exp_layout)
    ExpandableLayout mExpLayout;
    @BindView(R.id.statusBar)
    View mStatusView;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.toolbarLayout)
    LinearLayout mToolbarLayout;
    @BindView(R.id.activity_main)
    FrameLayout activityMain;
    private Unbinder unbinder;
    //    private List<ImageModel> banners = new ArrayList<>();
    private List<Double> fullHeights = new ArrayList<>();
    private String mTopicId;
    private OffcerDetailRe mDeatail;
    private List<ProinfosCon> mProList = new ArrayList<>();
    private List<String> mPicTopList = new ArrayList<>();
    private int Counter;


    public static ADProductDetailRedFragment newInstance(Product product, String topicId) {

        Bundle args = new Bundle();
        args.putString("topicId", topicId);
        mProduct = product;
        ADProductDetailRedFragment fragment = new ADProductDetailRedFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTopicId = getArguments().getString("topicId");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ad_fragment_product_red_detail, container, false);
        View tpview = attachToSwipeBack(view);
        unbinder = ButterKnife.bind(this, tpview);
        mToolbarLayout.setAlpha(0);
        mRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));


        List<String> tmpList = new ArrayList<>();
        tmpList.add("aaa");
        tmpList.add("aaa");
        tmpList.add("aaa");
        tmpList.add("bbb");
        tmpList.add("bbb");
        mRecyclerview.setAdapter(new CommonAdapter<String>(getActivity(), R.layout.item_sample, tmpList) {
            @Override
            protected void convert(ViewHolder viewHolder, final String item, int position) {

            }
        });

        mToolbar.post(() -> {
            mExpLayout.setMinMargin(mToolbar.getHeight() + mStatusView.getHeight());
            mExpLayout.setThreshold(mToolbar.getHeight() + mStatusView.getHeight());
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mStatusView.getLayoutParams().height = Utils.getStatusBarHeight(getContext());
        }
        mExpLayout.setUpWithHeader(mExpHeader);
        mExpLayout.setOnLayoutScrollListener(scrollDistance -> changeToolbar());


        return tpview;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        RetrofitClient.getPDAClient().create(AdService.class).experienceDetails(new Actis(mTopicId))               //获取Observable对象
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<OffcerDetail>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);

                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onNext(BOb<OffcerDetail> offcerDetailBOb) {
                        Repo.initRepo();
                        mDeatail = offcerDetailBOb.getBody().getDetails();
                        List<ProinfosCon> porList = mDeatail.getPro_list();
                        List<String> picTopList = mDeatail.getPic_list();
                        mProList = porList;
                        mPicTopList = picTopList;
                        Observable.create((Observable.OnSubscribe<Integer>) subscriber -> Observable.from(picTopList)
                                .map(s -> {
                                    Glide.with(getContext().getApplicationContext())
                                            .asBitmap()
                                            .load(s)
                                            .into(new SimpleTarget<Bitmap>() {
                                                @Override
                                                public void onResourceReady(Bitmap bitmap,
                                                                            Transition<? super Bitmap> transition) {
                                                    int width = bitmap.getWidth();
                                                    int height = bitmap.getHeight();

                                                    Double radio = Double.valueOf(height / width);
                                                    Double HH = (double) Utils.getDisplayWidth((AppCompatActivity) getActivity());

                                                    radio = radio - Math.random() * radio / 3;

                                                    fullHeights.add(HH * radio);
                                                    subscriber.onNext(0);
                                                    Counter++;
                                                    L.d("hcia", "radio:" + radio);
                                                    L.d("hcia", "Counter:" + Counter);
                                                    if (Counter == picTopList.size()) {
                                                        subscriber.onCompleted();
                                                    }
                                                }
                                            });
                                    return s;
                                }).subscribe(s -> {

                                })).subscribe(new Subscriber<Integer>() {
                            @Override
                            public void onCompleted() {
                                L.d("hcia", "onCompleted:!!!!!!!!!!");
                                Counter = 0;
                                mHeaderPager.setAdapter(new PagerAdapter() {

                                    private LayoutInflater inflater;

                                    @Override
                                    public int getCount() {
                                        return mPicTopList.size();
                                    }

                                    @Override
                                    public boolean isViewFromObject(View view, Object object) {
                                        return view == object;
                                    }

                                    @Override
                                    public Object instantiateItem(ViewGroup container, int position) {
                                        this.inflater = (LayoutInflater) getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);
                                        ImageView imageView = (ImageView) inflater.inflate(R.layout.layout_banner_image, container, false);

                                        Glide.with(getContext().getApplicationContext())
                                                .asBitmap()
                                                .load(mPicTopList.get(position))
                                                .into(new SimpleTarget<Bitmap>() {
                                                    @Override
                                                    public void onResourceReady(Bitmap bitmap,
                                                                                Transition<? super Bitmap> transition) {
                                                        imageView.setImageBitmap(bitmap);
                                                    }
                                                });

                                        container.addView(imageView);


                                        return imageView;
                                    }

                                    @Override
                                    public void destroyItem(ViewGroup container, int position, Object object) {
                                        container.removeView((View) object);
                                    }
                                });
                                mHeaderPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                    @Override
                                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                                        if (position == fullHeights.size() - 1) {
                                            return;
                                        }

                                        int height = (int) ((fullHeights.get(position) == 0 ? fullHeights.get(0) : fullHeights.get(position))
                                                * (1 - positionOffset) +
                                                (fullHeights.get(position + 1) == 0 ? fullHeights.get(0) : fullHeights.get(position + 1))
                                                        * positionOffset);
                                        mExpHeader.setHeight(height);
                                    }

                                    @Override
                                    public void onPageSelected(int position) {
                                    }

                                    @Override
                                    public void onPageScrollStateChanged(int state) {

                                    }
                                });


                                mExpHeader.setHeight(fullHeights.get(0).intValue());
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(Integer integer) {

                            }
                        });

                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    public void changeToolbar() {
        float alpha = (float) (mExpLayout.getThreshold() - mExpLayout.getTopMargin() + mExpLayout.getMinMargin()) / mExpLayout.getThreshold();
        setToolbarAlpha(alpha < 0 ? 0 : alpha);
    }

    public void setToolbarAlpha(float alpha) {
        mToolbarLayout.setAlpha(alpha);
    }

}
